package com.jianhua.appmarket.module.service.system.impl;

import com.jianhua.appmarket.common.util.SnowflakeKeyUtil;
import com.jianhua.appmarket.module.dao.system.OrgRoleDao;
import com.jianhua.appmarket.module.dao.system.RoleDao;
import com.jianhua.appmarket.module.entity.system.OrgRole;
import com.jianhua.appmarket.module.entity.system.Role;
import com.jianhua.appmarket.module.entity.system.User;
import com.jianhua.appmarket.module.model.system.RoleParam;
import com.jianhua.appmarket.module.model.system.RoleVO;
import com.jianhua.appmarket.module.model.system.UserVO;
import com.jianhua.appmarket.module.service.system.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class RoleService implements IRoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private OrgRoleDao orgRoleDao;


    @Override
    public List<RoleVO> listRolesByOrgId(Long orgId) {
        RoleParam param = new RoleParam();
        param.setOrgId(orgId);
        return roleDao.listByParam(param);
    }

    @Override
    public Boolean addOrEditRole(Role role, UserVO user) {
        if(Objects.isNull(role.getId())){
            role.setId(SnowflakeKeyUtil.generateId());
            role.setCreateUser(user.getNickName());
            role.setUpdateUser(user.getNickName());

            OrgRole orgRole = new OrgRole();
            orgRole.setId(SnowflakeKeyUtil.generateId());
            orgRole.setRoleId(role.getId());
            orgRole.setOrgId(user.getOrgId());
            orgRole.setCreateUser(user.getNickName());
            orgRole.setUpdateUser(user.getNickName());
            return roleDao.insert(role) > 0 && orgRoleDao.insert(orgRole) > 0;
        }else {
            return editRole(role,user);
        }
    }

    @Override
    public Boolean editRole(Role role, User user) {
        role.setUpdateUser(user.getNickName());
        return roleDao.update(role) > 0;
    }


    @Override
    @Transactional
    public Boolean deleteRole(Long roleId) {
        OrgRole orgRole = new OrgRole();
        orgRole.setRoleId(roleId);
        return roleDao.deleteById(roleId) > 0 && orgRoleDao.deleteByParam(orgRole) > 0;
    }
}
